package com.appwx.sdk.app;

import java.util.Iterator;
import java.util.Stack;

import android.app.Activity;

/**
 * ActivityManager  Activity堆栈管理器
 * @author xiajun
 */
public class ActivityManager {
	private static Stack<Activity> activityStack;
	private static ActivityManager instance;

	private ActivityManager() {
	}

	public static ActivityManager getActivityManager() {
		if (instance == null) {
			instance = new ActivityManager();
		}
		return instance;
	}

	// 退出栈顶Activity
	public void popActivity(Activity activity) {
		if (activity != null) {
			// 在从自定义集合中取出当前Activity时，也进行了Activity的关闭操作
			activity.finish();
			activityStack.remove(activity);
			activity = null;
		}
	}

	// 获得当前栈顶Activity
	public Activity currentActivity() {
		Activity activity = null;
		if (!activityStack.empty())
			activity = activityStack.lastElement();
		return activity;
	}
	
	/**
	 * getActivityByClasss
	 * @param cls
	 * @return 
	 * TODO
	 * @exception 
	 * @since  1.0.0
	*/
	public Activity getActivityByClasss(Class cls) {
		Activity activity = null;
		if (activityStack.empty()){
			return activity;
		}
		Iterator<Activity> iterator = activityStack.iterator();
		for (int i = activityStack.size()-1; i >= 0; i--) {
			activity = activityStack.get(i);
			if(activity.getClass().equals(cls)){
				break;
			}
			activity = null;
		}
		return activity;
	}

	// 将当前Activity推入栈中
	public void pushActivity(Activity activity) {
		if (activityStack == null) {
			activityStack = new Stack<Activity>();
		}
		activityStack.add(activity);
	}

	// 退出栈中所有Activity
	public void popAllActivityExceptOne(Class cls) {
		if(cls == null){
//			MetooService.
		}
		while (true) {
			Activity activity = currentActivity();
			if (activity == null) {
				break;
			}
			if (activity.getClass().equals(cls)) {
				break;
			}
			popActivity(activity);
		}
	}
}

